import React, { useEffect, useState } from 'react';
import MovieCard from '../components/MovieCard';
import { searchMovies, getPopularMovies } from '../services/api';
import '../css/Home.css';
const Home = () => {
    const [searchQuery, setSearchQuery] = useState('');
    const [movies, setMovies] = useState([]);
    const [error, setError] = useState(null);
    const [loading, setLoading] = useState(true);

    // 搜索电影
    const handleSearch = async (e) => {
        // 表单提交默认会刷新页面，所以阻止默认行为
        e.preventDefault()
        if (searchQuery.trim() === '') {
            alert('请输入电影名');
            return;
        }
        if(loading) {
            alert('正在加载，请稍后再试');
            return;
        }
        setLoading(true);
        try {
            const filterMovies = await searchMovies(searchQuery.trim());
            setMovies(filterMovies);
            setError(null)
        }
        catch (error) {
            console.log('error', error)
            setError('请求失败,请查看网络或服务器状态');
        }
        finally {
            setLoading(false);
        }
    }

    useEffect(() => {
        const loadPopularMovies = async () => {
            try {
                const popularMovies = await getPopularMovies();
                setMovies(popularMovies);
            }
            catch (error) {
                console.log('error', error)
                setError('请求失败,请查看网络或服务器状态');
            }
            finally {
                setLoading(false);
            }
        }
        loadPopularMovies()
    }, [])

    return (
        <div className='home'>
            <form onSubmit={handleSearch} className='search-form'>
                <input type="text" placeholder='请输入电影名' className='search-input' value={searchQuery} onChange={(e) => setSearchQuery(e.target.value)} />
                <button type='submit' className='search-button'>搜索</button>
            </form>
            { error && <div className='error-message'>{error}</div> }
            {loading ? <div className='loading'>加载中...</div> :
                <div className='movies-grid'>
                    {movies.map(
                        // movie.title.toLowerCase().includes(searchQuery) && ()
                        (movie) => (
                            <MovieCard movie={movie} key={movie.id} ></MovieCard>
                        )
                    )}
                </div>
            }
        </div>
    );
};
export default Home;